<template>
  <div class="databasequestionListBody">
    <!-- 页头 -->
    <div class="header">
      <el-page-header
        :content="'《' + databaseData.title + '》试题列表'"
        @back="goBack"
      />
      <div>
        <el-button style="font-size: 12px" @click="toAdd">添加试题</el-button>
        <el-button
          type="primary"
          size="default"
          style="font-size: 12px"
          @click="toAdds"
          >批量添加试题</el-button
        >
      </div>
    </div>
    <!-- 查询 -->
    <div class="operate">
      <span>题目名称:</span>
      <!-- 题库名称input -->
      <div class="key">
        <el-input
          v-model="params.key"
          class="w-50 m-2 keyInput"
          placeholder="请输入题目名称"
          clearable
        />
      </div>
      <span>创建人:</span>
      <!-- 题库名称input -->
      <div class="admin">
        <el-input
          v-model="params.admin"
          class="w-50 m-2 keyInput"
          placeholder="请输入创建人"
          clearable
        />
      </div>
      <span>题目类型:</span>
      <!-- 题目类型 -->
      <div class="admin">
        <el-select v-model="params.type" clearable placeholder="请选择">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      <!-- 查询按钮 -->
      <el-button
        type="primary"
        style="font-size: 12px; margin-left: 10px; width: 60px; height: 30px"
        @click="inquire"
        >查询</el-button
      >
      <!-- 批量删除按钮 -->
      <el-button
        type="danger"
        :disabled="multipleSelection.length === 0 ? true : false"
        @click="dels"
        style="font-size: 12px; margin-left: 10px; width: 70px; height: 30px"
        >批量删除</el-button
      >
      <el-button
        style="font-size: 12px; margin-left: 10px; width: 80px; height: 30px"
        @click="exportExcelBtn"
        >导出excel</el-button
      >
    </div>
    <div class="table" id="table">
      <!-- 表格 -->
      <el-table
        ref="multipleTableRef"
        :data="tableData"
        style="width: 100%"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        :header-cell-style="{ backgroundColor: '#fafafa' }"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="题目名称" width="550">
          <template #default="scope">
            <el-button
              link
              type="primary"
              size="small"
              v-html="rep(scope.row.title)"
              @click="toLook(scope.row)"
            >
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          property="type"
          label="题量类型"
          show-overflow-tooltip
        />
        <el-table-column
          property="addtime"
          label="创建时间"
          show-overflow-tooltip
          ><template #default="scope">
            <span>{{ scope.row.addtime.substr(0, 16) }}</span>
          </template></el-table-column
        >
        <el-table-column
          label="创建人"
          property="admin"
          show-overflow-tooltip
        />
        <el-table-column fixed="right" label="操作" show-overflow-tooltip>
          <template #default="scope">
            <!-- 编辑按钮 -->
            <el-button
              link
              text
              type="primary"
              size="small"
              @click="toUpd(scope.row)"
            >
              编辑
            </el-button>

            <!-- 删除按钮 -->
            <el-button
              link
              type="primary"
              size="small"
              @click.prevent="deleteRow(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="demo-pagination-block">
        <el-pagination
          v-model:currentPage="params.page"
          v-model:page-size="params.psize"
          :page-sizes="[10, 20, 30, 100]"
          :small="small"
          :disabled="disabled"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="counts"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
  <!-- 查看试题组件 -->
  <CheckExam v-if="isLook"></CheckExam>
  <!-- 试题添加修改组件 -->
  <DatabasequestionAdd
    :is="drawer"
    @is-open="isOpen"
    :dataUp="dataUp"
    :databaseid="databaseData.id"
    v-if="drawer"
  ></DatabasequestionAdd>
  <Import
    @imports="imports"
    :isImport="isImport"
    @isImports="isImports"
  ></Import>
</template>

<script lang="ts" setup>
import { reactive, toRefs, ref, onMounted, provide } from "vue";
import { useRoute, useRouter } from "vue-router";
// 导入api
import {
  getDatabasequestionList,
  databasequestionDels,
  databasequestionDel,
  postDatabasequestionAddlist,
} from "../../apis/databaselist/databaselist";
import { ElTable, ElMessage, ElMessageBox } from "element-plus";
// 导入试题添加组件
import DatabasequestionAdd from "../../components/Databasequestion/DatabasequestionAdd.vue";
// 导入查看试题组件
import CheckExam from "../../components/Databasequestion/CheckExam.vue";
// 导入批量上传组件
import Import from "../../components/test/Import.vue";
import * as FileSaver from 'file-saver'
import  * as XLXS from 'xlsx';

// 存放响应式数据
const data: any = reactive({
  // 试卷数据
  databaseData: { id: "", title: "" },
  // 是否打开试题
  isLook: false,
  //   加载效果
  loading: true,
  //   表格数据
  tableData: [],
  //   复选框选中的数据
  multipleSelection: [],
  // 要修改的数据
  dataUp: {},
  //   列表请求数据
  params: {
    databaseid: 0,
    page: 1,
    psize: 10,
    key: "",
    tags: "",
    type: "",
    admin: "",
  },
  counts: 0,
  small: false,
  background: false,
  disabled: false,
  drawer: false,
  isImport: false, //批量添加弹框是否打开
});
// 解构data数据
const {
  isLook,
  isImport,
  dataUp,
  drawer,
  databaseData,
  loading,
  tableData,
  multipleSelection,
  params,
  counts,
  small,
  disabled,
} = toRefs(data);
provide("data", data);

// 点击跳转
const router = useRouter();
// 选择试题类型
const options = [
  {
    value: "单选题",
    label: "单选题",
  },
  {
    value: "多选题",
    label: "多选题",
  },
  {
    value: "判断题",
    label: "判断题",
  },
  {
    value: "填空题",
    label: "填空题",
  },
  {
    value: "问答题",
    label: "问答题",
  },
];
// 接受参数并存入databaseData中
const route = useRoute();
const supData: any = route.query.data;
data.databaseData = JSON.parse(supData);
params.value.databaseid = JSON.parse(supData).id;
// 替换下划线方法
const rep = (title: string) => {
  return title.replace(/\[\]/g, "_____,");
};
// 点击返回
const goBack = () => {
  router.push("databaselist");
};
// 子向父传过来的数据
const isOpen = (e: any) => {
  if (!e[0]) {
    drawer.value = e[0];
  }
  loading.value = e[1];
  databasequestionList(params.value);
};
// 点击添加
const toAdd = () => {
  drawer.value = true;
  dataUp.value = {
    id: 0,
    databaseid: 0,
    type: "单选题",
    tags: "",
    // 内容 HTML
    title: "",
    answer: "",
    scores: null,
    explains: "",
    answers: [
      {
        answerno: "A",
        content: "",
      },
      {
        answerno: "B",
        content: "",
      },
      {
        answerno: "C",
        content: "",
      },
      {
        answerno: "D",
        content: "",
      },
    ],
  };
};
// 点击编辑
const toUpd = (data: any) => {
  drawer.value = true;
  dataUp.value = data;
  console.log(data);
};
// 请求列表数据
const databasequestionList = async (params: any) => {
  const res: any = await getDatabasequestionList(params);
  console.log(res);
  
  if (res.errCode === 10000) {
    tableData.value = res.data.list;
    loading.value = false;
    counts.value = res.data.counts;
  } else {
    ElMessage.error(res.errMsg);
  }
};
onMounted(() => {
  databasequestionList(params.value);
});
// 复选框选内容改变
const handleSelectionChange = (data: any) => {
  multipleSelection.value = data;
};
// 点击删除单条数据
const deleteRow = (id: number) => {
  console.log(id);
  ElMessageBox.confirm("此操作将永久删除该文件, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      loading.value = true;
      const res: any = await databasequestionDel(id);
      if (res.errCode === 10000) {
        ElMessage({
          type: "success",
          message: "删除成功",
        });
        databasequestionList(params.value);
      } else {
        ElMessage({
          type: "info",
          message: res.errMsg,
        });
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消删除！",
      });
    });
};
// 点击查询
const inquire = () => {
  params.value.page = 1;
  databasequestionList(params.value);
};
// 点击批量删除
const dels = () => {
  const ids = multipleSelection.value.map((item: any) => item.id);
  ElMessageBox.confirm("此操作将永久删除选中的文件, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      loading.value = true;
      const res: any = await databasequestionDels(ids);
      if (res.errCode === 10000) {
        ElMessage({
          type: "success",
          message: "删除成功",
        });
        databasequestionList(params.value);
      } else {
        ElMessage({
          type: "info",
          message: res.errMsg,
        });
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消删除！",
      });
    });
};
// 每页多少条内容改变
const handleSizeChange = (val: number) => {
  params.value.psize = val;
  databasequestionList(params.value);
  loading.value = true;
};
// 页码内容改变
const handleCurrentChange = (val: number) => {
  params.value.page = val;
  databasequestionList(params.value);
  loading.value = true;
};
// 替换下划线方法
const repTitle = (title: string) => {
  return title.replace(/\[\]/g, "_____,");
};
// 点击查看试题
const toLook = (examInfo: any) => {
  data.isLook = true;
  data.dataUp = { ...examInfo, title: repTitle(examInfo.title) };
};
// 批量添加
const toAdds = () => {
  data.isImport = true;
};
// 接受批量添加传来的数据
const isImports = (e: any) => {
  data.isImport = e;
};
// 请求批量添加接口
const databasequestionAddlist = async (param: any) => {
  const res: any = await postDatabasequestionAddlist(param);
  if (res.errCode === 10000) {
    databasequestionList(params.value);
    ElMessage({
      type: "success",
      message: "添加成功",
    });
  } else {
    ElMessage({
      type: "error",
      message: res.errMsg,
    });
  }
};
// 批量添加
const imports = (e: any) => {
  console.log(e);
  const AddlistParams = {
    databaseid: data.params.databaseid,
    list: e.map((item: any) => ({
      title: item.title,
      type: item.type,
      answer: item.answer,
      tags: item.tags,
      explains: item.explains,
      answers: item.answers,
    })),
  };
  // console.log(AddlistParams);
  databasequestionAddlist(AddlistParams);
};
// 点击批量导出
const exportExcelBtn = () => {
  // 设置当前日期
  const filename = data.databaseData.title; // 通过id，获取导出的表格数据
  const wb = XLXS.utils.table_to_book(document.getElementById("table"), {
    raw: true,
  });
  console.log(wb);
  
  const wbout = XLXS.write(wb, {
    bookType: "xlsx",
    bookSST: true,
    type: "array",
  });
  try {
    FileSaver.saveAs(
      new Blob([wbout], {
        type: "application/octet-stream",
      }),
      filename + ".xlsx"
    );
  } catch (e) {
    console.log(e);
  }
  return wbout;
};
</script>

<style lang="less" scoped>
@import url("../../static/css/databaselist/databasequestionList.css");
</style>
